package com.hnyyjsxy.dao.impl;

import com.hnyyjsxy.dao.UserDao;
import com.hnyyjsxy.domain.AccountSheet;
import com.hnyyjsxy.domain.Student;
import com.hnyyjsxy.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * @date 2021/02/04
 */
public class UserDaoImpl implements UserDao {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());

    /**
     * 判断该学号是否存在
     * @param sid
     * @return 如果存在返回true
     */
    @Override
    public boolean findBySid(String sid) {
        Student student = null;
        //如果没有查找到会有异常
        try {
            String sql = "SELECT * FROM student WHERE sid=?";
            student = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Student>(Student.class), sid);
        }catch (Exception e){
        }
        return student!=null;
    }

    /**
     * 学生注册，进行数据库写入
     * @param student 学生信息
     */
    @Override
    public void register(Student student) {
        String sql = "INSERT INTO student (sid,sname,gender,squad,email,phone,building,room,bed,charge) VALUE(?,?,?,?,?,?,?,?,?,0)";
        jdbcTemplate.update(sql,student.getSid(),student.getSname(),student.getGender(),student.getSquad(),student.getEmail(),student.getPhone(),student.getBuilding(),student.getRoom(),student.getBed());
    }

    /**
     * 学生注册，写入账号表
     * @param username
     * @param password
     */
    @Override
    public void addAccount(String username, String password) {
        String sql = "INSERT INTO account_sheet(account,a_password,identity) VALUE(?,?,1)";
        jdbcTemplate.update(sql,username,password);
    }

    /**
     * 用户的登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public AccountSheet userlogin(String username, String password) {
        AccountSheet accountSheet = null;
        try{
            String sql = "SELECT * FROM account_sheet WHERE account=? AND a_password=?";
            accountSheet = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<AccountSheet>(AccountSheet.class),username,password);
        }catch(Exception e){
        }
        return accountSheet;
    }
}
